package com.xinqiupark.technology.ui.adapter;

import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;

import com.xinqiupark.technology.R;
import com.xinqiupark.technology.image.ImageLoader;
import com.xinqiupark.technology.view.SquareImageView;

import java.util.List;

/**
 * @author Steven.zhao
 * email:hongtu.zhao@goodwinsoft.net
 * date:2018/7/22
 * desc:图片适配器
 */
public class ImageAdapter extends BaseAdapter {

    private List<String> mUrList;

    private LayoutInflater mInflater;

    private BitmapDrawable mDefaultDrawable;

    private ImageLoader mImageLoader;

    private int mImageWidth;

    private boolean mIsGridViewIdle;

    private boolean mCanGetBitmapFromNetWork;


    public ImageAdapter(Context context) {
        mDefaultDrawable=new BitmapDrawable(BitmapFactory.decodeResource(context.getResources(),R.drawable.ic_launcher_foreground));
        mInflater = LayoutInflater.from(context);

        mImageLoader=ImageLoader.build(context);
    }

    public void setUrList(List<String> urList) {
        mUrList = urList;

        notifyDataSetChanged();
    }

    public void setGridViewIdle(boolean gridViewIdle) {
        mIsGridViewIdle = gridViewIdle;
    }

    public void setCanGetBitmapFromNetWork(boolean canGetBitmapFromNetWork) {
        mCanGetBitmapFromNetWork = canGetBitmapFromNetWork;
    }

    @Override
    public int getCount() {
        return mUrList!=null?mUrList.size():0;
    }

    @Override
    public String getItem(int position) {
        return mUrList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder=null;

        if(convertView==null)
        {
            convertView=mInflater.inflate(R.layout.layout_image_loader,parent,false);
            holder=new ViewHolder();
            holder.mImageView=convertView.findViewById(R.id.image);
            convertView.setTag(holder);
        }
        else
        {
            holder= (ViewHolder) convertView.getTag();
        }
        ImageView imageView=holder.mImageView;
        mImageWidth=imageView.getWidth();
        final String tag=(String)imageView.getTag();
        final String uri=getItem(position);
        if(!uri.equals(tag))
        {
            imageView.setImageDrawable(mDefaultDrawable);
        }

        if(mIsGridViewIdle && mCanGetBitmapFromNetWork)
        {
            imageView.setTag(uri);
            mImageLoader.bindBitmap(uri,imageView,mImageWidth,mImageWidth);
        }
        return convertView;
    }

    static class ViewHolder{
        public SquareImageView mImageView;
    }
}
